// 引入express创建服务器，端口
const express = require("express");
const app = express();

//跨域设置
const cors = require("cors");
app.use(
  cors({
    origin: [
      "http://localhost:8848",
      "http://127.0.0.1:8848",
      "http://localhost:8080",
      "http://127.0.0.1:8080",
      "http://localhost:8081",
      "http://127.0.0.1:8081",
      "http://localhost:5500",
      "http://127.0.0.1:5500",
    ], //指定接收的地址
    methods: ["GET", "POST", "DELETE", "PUT"], //指定接收的请求类型
    alloweHeaders: ["Content-Type", "Authorization"], //指定header
  })
);

// 数据库
const mysql = require("mysql");
const pool = mysql.createPool({
  host: "127.0.0.1",
  port: "3306",
  user: "root",
  password: "",
  database: "xsp",
  connectionLimit: 15,
  charset: "utf8",
});

//配置multer中间件
const multer = require("multer");
obj = multer.diskStorage({
  destination: function (req, file, cb) {
    //指定目录
    cb(null, "public");
  },
  filename: function (req, file, cb) {
    // 指定文件名
    let name = file.originalname;
    // name:  abcd.jpg    xxxdfdd.zip
    let ext = name.substr(name.lastIndexOf("."));
    cb(null, uuid.v4() + ext);
  },
});
const uploadTools = multer({
  storage: obj,
});
const uuid = require("uuid");

//设置端口
app.listen(3000);
console.log("创建成功");

//托管静态资源
app.use(express.static("./public"));

//接收请求
app.post("/upload", uploadTools.array("uploadFile"), (req, res) => {
  // console.log(req.files)
  let urls = [];
  req.files.forEach((item) => {
    urls.push(`http://localhost:3000/${item.filename}`);
  });
  res.send({ code: 200, msg: "ok", urls });
});

//将post对象传递的参数转为对象
app.use(express.urlencoded({ extended: true }));

// 登录接口/login
app.post("/login", (req, res, next) => {
  var obj = req.body;
  //验证登录账号
  pool.query("select * from xsp_user where uname=?", [obj.uname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (!r[0]) {
      //如果未查询到用户则账号密码错误
      res.send({ code: 500, msg: "账号密码错误" });
    } else if (obj.uname == "Admingly" && obj.upwd == r[0].upwd) {
      res.send({ code: 222, msg: "管理员登录成功", data: r });
    } else if (obj.upwd == r[0].upwd) {
      res.send({ code: 200, msg: "登录成功", data: r });
    } else {
      res.send({ code: 500, msg: "账号密码错误" });
    }
  });
});
// 手机登录
app.post("/login1", (req, res, next) => {
  var obj = req.body;
  //验证登录手机号码
  pool.query("select * from xsp_user where phone=?", [obj.phone], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (!r[0]) {
      //如果未查询到用户则账号密码错误
      res.send({ code: 500, msg: "账号密码错误" });
    } else if (obj.upwd == r[0].upwd) {
      res.send({ code: 200, msg: "登录成功", data: r });
    } else {
      res.send({ code: 500, msg: "账号密码错误" });
    }
  });
});

//验证接口
app.post("/index1", (req, res, next) => {
  var obj = req.body;
  pool.query("select * from xsp_user where ?", [obj], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (!r[0]) {
      res.send({ code: 200, msg: "可以使用" });
    } else {
      res.send({ code: 500, msg: "不可以使用" });
    }
  });
});
// 注册接口/register
app.post("/register", (req, res, next) => {
  var obj = req.body;
  pool.query("insert into xsp_user set?", [obj], (err, r) => {
    if (err) {
      next(err);
      return;
    } else {
      res.send({ code: 200, msg: "注册成功" });
    }
  });
});
//手机注册接口
app.post("/registersj", (req, res, next) => {
  var obj = req.body;
  // console.log(obj)
  // 随机起名
  let sjxm = "";
  function sj() {
    sjxm = "用户" + Math.floor(Math.random() * 9999999);
    return sjxm;
  }
  sj();
  // console.log(sjxm)
  function yz() {
    pool.query(`select uname from xsp_user where uname="${sjxm}"`, (err, r) => {
      if (err) {
        next(err);
        return;
      }
      if (r[0]) {
        sj();
        yz();
      } else {
        pool.query(
          `insert into xsp_user set?,uname='${sjxm}'`,
          [obj],
          (err, r) => {
            if (err) {
              next(err);
              return;
            } else {
              res.send({
                code: 200,
                msg: "注册成功",
                uname: sjxm,
                phone: obj.phone,
                upwd: obj.upwd,
              });
            }
          }
        );
      }
    });
  }
  yz();
});

// 发表食谱接口
app.post("/index2", (req, res, next) => {
  var obj = req.body;
  pool.query("insert into xsp_recipe set?", [obj], (err, r) => {
    if (err) {
      next(err);
      return;
    } else {
      // console.log(r)
      res.send({ code: 200, msg: "食谱添加成功", r_id: r.insertId });
    }
  });
});

// 添加上传图片接口
app.post("/index3", (req, res, next) => {
  var obj = req.body;
  pool.query("insert into xsp_img set?", [obj], (err, r) => {
    if (err) {
      next(err);
      return;
    } else {
      // console.log(r)
      res.send({ code: 200, msg: "图片添加成功", data: r });
    }
  });
});

// 查询用户信息接口
app.post("/ulist", (req, res, next) => {
  var obj = req.body;
  pool.query(
    "select * from xsp_user where uname=?",
    [obj.uname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, msg: "查询成功", data: data });
    }
  );
});

//用户列表接口
app.get("/list", (req, res, next) => {
  pool.query("select * from xsp_user", (err, data) => {
    if (err) {
      next(err);
      return;
    }
    res.send({
      code: 1,
      msg: "已查到数据",
      data: data,
    });
  });
});

//用户排行榜
app.get("/phblist", (req, res, next) => {
  pool.query(
    "select uid,uname,headp,signature,ulike,collection,fans,(ulike*2+collection*3+fans*10) zl from xsp_user order by ulike*2+collection*3+fans*10 desc limit 0,10",
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      res.send({
        code: 1,
        msg: "已查到数据",
        data: data,
      });
    }
  );
});

// 关注接口
app.post("/fans", (req, res, next) => {
  var obj = req.body;
  pool.query("insert into xsp_focus set?", [obj], (err, r) => {
    if (err) {
      next(err);
      return;
    } else {
      // console.log(r)
      res.send({ code: 200, msg: "关注成功", r: r });
    }
  });
});

//查询关注列表
app.post("/fanslist", (req, res, next) => {
  var obj = req.body;
  // console.log(obj)
  pool.query(
    "select * from xsp_focus where uname=? limit 0,7",
    [obj.uname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      // console.log(data)
      res.send({
        code: 1,
        msg: "已查到关注数据",
        data: data,
      });
    }
  );
});
//查询粉丝列表
app.post("/isfanslist", (req, res, next) => {
  var obj = req.body;
  // console.log(obj)
  pool.query(
    "select * from xsp_focus where focus_uname=? limit 0,7",
    [obj.focus_uname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      // console.log(data)
      res.send({
        code: 1,
        msg: "已查到粉丝数据",
        data: data,
      });
    }
  );
});

//用户关注的用户信息接口
app.post("/fansuserlist", (req, res, next) => {
  var obj = req.body;
  pool.query(
    "select *,(ulike*2+collection*3+fans*10) zl from xsp_user where uname=? order by ulike*2+collection*3+fans*10 desc limit 0,7",
    [obj.uname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      res.send({
        code: 1,
        msg: "粉丝已查到数据",
        data: data,
      });
    }
  );
});

// 收藏接口
app.post("/collection", (req, res, next) => {
  var obj = req.body;
  pool.query(
    "select * from xsp_collection where uname=? && collection_rid=?",
    [obj.uname, obj.collection_rid],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      console.log(data);
      if (!data[0]) {
        pool.query("insert into xsp_collection set?", [obj], (err, r) => {
          if (err) {
            next(err);
            return;
          } else {
            // console.log(r)
            res.send({ code: 200, msg: "收藏成功", r: r });
          }
        });
      } else {
        res.send({ code: 300, msg: "已收藏" });
      }
    }
  );
});
//查询收藏列表
app.post("/mysclist", (req, res, next) => {
  var obj = req.body;
  // console.log(obj)
  pool.query(
    "select * from xsp_collection where uname=? limit 0,7",
    [obj.uname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      // console.log(data)
      res.send({
        code: 1,
        msg: "已查到收藏数据",
        data: data,
      });
    }
  );
});

//查询食谱详细信息接口
app.post("/relist", (req, res, next) => {
  var obj = req.body;
  pool.query(
    "select * from xsp_recipe where rname=?",
    [obj.rname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, msg: "查询成功", data: data });
    }
  );
});

// select * from emp where ename like '%e_';
// 模糊查询食谱详细信息接口
app.post("/mhlist", (req, res, next) => {
  var obj = req.body;
  // console.log(obj)
  pool.query(
    `select * from xsp_recipe where rname like '%${obj.rname}%' `,
    [obj.rname],
    (err, data) => {
      // console.log(data)
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, msg: "查询成功", data: data });
    }
  );
});

// ID查询食谱详细信息接口
app.post("/ridlist", (req, res, next) => {
  var obj = req.body;
  pool.query("select * from xsp_recipe where rid=?", [obj.rid], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    res.send({ code: 200, msg: "查询成功", data: data });
  });
});

// 查询食谱信息接口
app.post("/sppfllist", (req, res, next) => {
  var obj = req.body;
  pool.query("select * from xsp_recipe cid=?", [obj.cid], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    res.send({ code: 200, msg: "食谱数据查询成功", data: data });
  });
});

//食谱列表接口
app.get("/rlist", (req, res, next) => {
  pool.query("select * from xsp_recipe order by rid asc", (err, data) => {
    if (err) {
      next(err);
      return;
    }
    res.send({
      code: 1,
      msg: "已查到数据",
      data: data,
    });
  });
});

//查询食谱信息接口
app.post("/sppfllista", (req, res, next) => {
  var obj = req.body;
  pool.query(
    "select * from xsp_recipe where cname=?",
    [obj.cname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, msg: "查询成功", data: data });
    }
  );
});
//查询食谱信息(分页，每页6个)接口
app.post("/spfllist", (req, res, next) => {
  var obj = req.body;
  pool.query(
    "select*from xsp_recipe where cname=? limit 0,6;",
    [obj.cname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, msg: "查询成功", data: data });
    }
  );
});

// select uid,uname,headp,signature,ulike,collection,fans,(ulike*2+collection*3+fans*10) zl from xsp_user order by ulike*2+collection*3+fans*10 desc limit 0,10
//用户名称查询食谱信息(分页，每页7个)接口
app.post("/usersplist", (req, res, next) => {
  var obj = req.body;
  pool.query(
    "select *,(score*10+r_collection*3+r_read) rq from xsp_recipe where r_uname=? order by (score*10+r_collection*3+r_read) desc limit 0,7;",
    [obj.r_uname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, msg: "用户食谱查询成功", data: data });
    }
  );
});

//分类列表接口
app.get("/fllist", (req, res, next) => {
  pool.query("select * from xsp_class", (err, data) => {
    if (err) {
      next(err);
      return;
    }
    res.send({
      code: 1,
      msg: "已查到数据",
      data: data,
    });
  });
});
// 修改用户信息接口
app.post("/xglist", (req, res, next) => {
  var obj = req.body;
  pool.query(
    "update xsp_user set signature=? where uname=?",
    [obj.signature, obj.uname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, msg: "修改成功", data: data });
    }
  );
});

// 修改密码信息接口
app.post("/xgmmlist", (req, res, next) => {
  var obj = req.body;
  pool.query(
    "select upwd from xsp_user where uname=?",
    [obj.uname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      // console.log(data[0].upwd,obj.jdmm)
      if (data[0].upwd == obj.jdmm) {
        pool.query(
          "update xsp_user set upwd=? where uname=?",
          [obj.xdmm, obj.uname],
          (err, data) => {
            if (err) {
              next(err);
              return;
            } else {
              res.send({ code: 200, msg: "修改成功" });
            }
          }
        );
      } else {
        res.send({
          code: 400,
          msg: "旧的密码填写错误",
        });
      }
    }
  );
});
// 修改手机号码信息接口
app.post("/xgsjlist", (req, res, next) => {
  var obj = req.body;
  pool.query(
    "select upwd from xsp_user where uname=?",
    [obj.uname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      // console.log(data[0].upwd,obj.jdmm)
      if (data[0].upwd == obj.jdmm) {
        pool.query(
          "update xsp_user set phone=? where uname=?",
          [obj.phone, obj.uname],
          (err, data) => {
            if (err) {
              next(err);
              return;
            }
            res.send({ code: 200, msg: "修改成功" });
          }
        );
      } else {
        res.send({
          code: 400,
          msg: "旧的密码填写错误",
        });
      }
    }
  );
});
// 修改头像信息接口
app.post("/xgtxlist", (req, res, next) => {
  var obj = req.body;
  pool.query(
    "update xsp_user set headp=? where uname=?",
    [obj.headp, obj.uname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, msg: "修改成功", data: data });
    }
  );
});
// 修改空间是否开放接口
app.post("/xgkjlist", (req, res, next) => {
  var obj = req.body;
  // console.log(obj.is_show)
  pool.query(
    "update xsp_user set is_show=? where uname=?",
    [obj.is_show, obj.uname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      // console.log(data)
      if (obj.is_show == "true") {
        res.send({ code: 200, msg: "开放空间成功", data: data });
      } else if (obj.is_show == "false") {
        res.send({ code: 201, msg: "关闭空间成功", data: data });
      }
    }
  );
});

//删除用户接口
app.delete("/del/:uid", (req, res, next) => {
  let obj = req.params;
  //删除语句
  pool.query("delete from xsp_user where uid=?", [obj.uid], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.affectedRows == 1) {
      res.send({ code: 1, msg: "删除成功" });
    } else {
      res.send({ code: 1, msg: "删除失败" });
    }
  });
});
//删除用户接口
app.post("/delyh", (req, res, next) => {
  let obj = req.body;
  // console.log(obj)
  pool.query(
    "select upwd from xsp_user where uname=?",
    [obj.uname],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      // console.log(data[0].upwd,obj.jdmm)
      if (data[0].upwd == obj.jdmm) {
        //删除语句
        pool.query(
          "delete from xsp_user where uname=?",
          [obj.uname],
          (err, r) => {
            if (err) {
              next(err);
              return;
            }
            if (r.affectedRows == 1) {
              res.send({ code: 1, msg: "删除成功" });
            } else {
              res.send({ code: 0, msg: "删除失败" });
            }
          }
        );
      } else {
        res.send({
          code: 400,
          msg: "旧的密码填写错误",
        });
      }
    }
  );
});

//删除粉丝接口
app.post("/delfs", (req, res, next) => {
  let obj = req.body;
  // console.log(obj)
  //删除语句
  pool.query(
    "delete from xsp_focus where uname=? && focus_uname=?",
    [obj.uname, obj.focus_uname],
    (err, r) => {
      if (err) {
        next(err);
        return;
      }
      if (r.affectedRows == 1) {
        res.send({ code: 1, msg: "删除成功" });
      } else {
        res.send({ code: 0, msg: "删除失败" });
      }
    }
  );
});

//删除食谱接口
app.delete("/del/:rid", (req, res, next) => {
  let obj = req.params;
  //删除语句
  pool.query("delete from xsp_recipe where rid=?", [obj.rid], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.affectedRows == 1) {
      res.send({ code: 1, msg: "删除成功" });
    } else {
      res.send({ code: 0, msg: "删除失败" });
    }
  });
});
//先查询评分表，如果没有则添加评分并计算平均分，然后修改食谱表的评分
app.post("/pflist", (req, res, next) => {
  var obj = req.body;
  // console.log(obj)
  pool.query(
    "select * from xsp_pf where pf_recipeid=? && username=?",
    [obj.pf_recipeid, obj.username],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      // console.log(data)
      if (data[0]) {
        res.send({ code: 333, msg: "您已评价过", data: data });
      } else {
        pool.query("insert into xsp_pf set?", [obj], (err, r) => {
          if (err) {
            next(err);
            return;
          }
          if (r.affectedRows == 1) {
            pool.query(
              "select score from xsp_pf where pf_recipeid=?",
              [obj.pf_recipeid],
              (err, data) => {
                if (err) {
                  next(err);
                  return;
                }
                // console.log(data)
                let sum = 0;
                let pf;
                data.forEach((e) => {
                  sum += e.score;
                });
                pf = ((sum + 50) / (data.length + 10)).toFixed(1);
                // console.log(pf)
                //修改评分
                pool.query(
                  "update xsp_recipe set score=? where rid=?",
                  [pf, obj.pf_recipeid],
                  (err, data) => {
                    if (err) {
                      next(err);
                      return;
                    }
                    // res.send({code:200,msg:"修改成功",data:data});
                  }
                );
                // console.log(sum/(data.length))
              }
            );
            res.send({ code: 200, msg: "评分成功" });
          } else {
            res.send({ code: 201, msg: "评分失败" });
          }
        });
      }
    }
  );
});

//查询评论接口
app.post("/pllist", (req, res, next) => {
  var obj = req.body;
  pool.query(
    "select * from xsp_review where recipeid=? order by reid desc",
    [obj.recipeid],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, msg: "查询成功", data: data });
    }
  );
});

//发表评论接口
app.post("/indexpl", (req, res, next) => {
  var obj = req.body;
  pool.query("insert into xsp_review set?", [obj], (err, r) => {
    if (err) {
      next(err);
      return;
    } else {
      res.send({ code: 200, msg: "添加成功" });
    }
  });
});

//在所有路由后边添加错误处理中间件
app.use((err, req, res, next) => {
  if (err) {
    console.log(err);
  }
  res.send({ code: 502, msg: "出错啦！" });
});
